<template>
	<view class="message-list-page">
		<!-- 1. 顶部区域 -->
		<view class="top-bar">
			<text class="page-title">消息</text>
			<view class="actions">
				<!-- <view class="action-item" @click="clearUnread">
					<uni-icons type="refreshempty" size="18" color="#555"></uni-icons>
					<text>清除未读</text>
				</view> --> 
				<!-- 根据需要可以添加更多操作，例如右上角的 "+" -->
				<!-- <uni-icons type="plus-filled" size="24" color="#333" @click="showMoreActions"></uni-icons> -->
			</view>
		</view>

		<!-- 2. 搜索框 -->
		<!-- <view class="search-bar-container">
			<view class="search-bar" @click="gotoSearch">
				<uni-icons type="search" size="18" color="#999"></uni-icons>
				<text class="placeholder">搜索聊天记录/联系人/服务号</text>
			</view>
		</view> -->

		<!-- 3. 消息会话列表 -->
		<scroll-view class="conversation-list" scroll-y @scrolltolower="loadMoreConversations">
			<view
				class="conversation-item"
				v-for="conv in conversations"
				:key="conv.id"
				@click="openConversation(conv)"
				:class="{ 'pinned': conv.isPinned }">
				<view class="avatar-container">
					<image class="avatar" :src="conv?.sender?.photo" mode="aspectFill"></image>
					<view class="unread-badge" v-if="conv.unreadCount > 0 && !conv.isMuted">
						{{ conv.unreadCount > 99 ? '99+' : conv.unreadCount }}
					</view>
					<view class="mute-dot" v-if="conv.unreadCount > 0 && conv.isMuted"></view>
					<image v-if="conv.statusIcon" :src="conv.statusIcon" class="status-icon" mode="aspectFit"></image>
				</view>

				<view class="content-container">
					<view class="title-line">
						<text class="name" :class="{'unread-name': conv.unreadCount > 0}">{{ conv.name }}</text>
						<text class="status-tag" v-if="conv.statusTag">{{ conv.statusTag }}</text>
						<text class="time">{{ conv.lastMessageTime }}</text>
					</view>
					<view class="message-line">
						<!--<text class="last-message" >{{ conv.content }}</text>-->
						<uni-icons v-if="conv.isMuted" type="sound-disable" size="16" color="#BDBDBD" class="mute-icon"></uni-icons>
					</view>
				</view>

				<image v-if="conv.previewImage" :src="conv.previewImage" class="preview-image" mode="aspectFill"></image>
			</view>
			
			<!-- 加载更多提示 -->
			<view class="loading-more" v-if="isLoadingMore">加载中...</view>
			<view class="no-more" v-if="!isLoadingMore && conversations.length > 0 && noMoreData">没有更多消息了</view>
			<view class="empty-state" v-if="conversations.length === 0 && !isLoadingInitial">
				<image src="/static/empty_message_list.png" mode="widthFix" class="empty-icon"></image>
				<text>暂无消息</text>
			</view>

		</scroll-view>
	</view>
</template>

<script>
const app = getApp()
export default {
	data() {
		return {
			conversations: [],
			isLoadingMore: false,
			isLoadingInitial: true,
			noMoreData: false, // 是否已加载所有数据
			page: 1, // 用于分页加载
		};
	},
	onShow(){
		this.loadInitialConversations()
	},
	onLoad() {
		// 通常消息列表页是 TabBar 页，导航栏标题在 pages.json 中配置
		// 如果不是 TabBar 页，可以在此设置标题：
		// uni.setNavigationBarTitle({ title: '消息' });
		this.loadInitialConversations();
	},
	onPullDownRefresh() { // 下拉刷新
		this.page = 1;
		this.conversations = [];
		this.noMoreData = false;
		this.loadInitialConversations().finally(() => {
			uni.stopPullDownRefresh();
		});
	},
	methods: {
		/**
		 * 计算时间差并返回人性化字符串（如“1分钟前”、“5小时前”）
		 * @param {Date|number} startTime 开始时间（Date对象或时间戳）
		 * @param {Date|number} [endTime] 结束时间（默认当前时间）
		 * @returns {string} 格式化后的时间差
		*/
		formatTimeAgo(startTime, endTime = new Date()) {
			console.log(startTime)
			// 统一转为时间戳（兼容Date对象和数字）
			const start = new Date(startTime).getTime();
			const end = new Date(endTime).getTime();
			
			// 计算时间差（毫秒）
			const diff = end - start;
			if (diff < 0) return "未来时间"; // 处理时间倒流
			
			// 时间差转换为秒/分/时/天
			const seconds = Math.floor(diff / 1000);
			const minutes = Math.floor(seconds / 60);
			const hours = Math.floor(minutes / 60);
			const days = Math.floor(hours / 24);
			
			// 根据时间差返回不同格式
			if (seconds < 10) return "刚刚";
			if (seconds < 60) return `${seconds}秒前`;
			if (minutes < 10) return "1分钟前";
			if (minutes < 30) return `${minutes}分钟前`;
			if (minutes < 60) return "30分钟前";
			if (hours < 5) return "1小时前";
			if (hours < 24) return `${hours}小时前`;
			if (days === 1) return "昨天";
			if (days < 7) return `${days}天前`;
			if (days < 30) return `${Math.floor(days / 7)}周前`;
			if (days < 365) return `${Math.floor(days / 30)}个月前`;
			return `${Math.floor(days / 365)}年前`;
		},
		async loadInitialConversations() {
			this.isLoadingInitial = true;
			// 模拟API请求
			await new Promise(resolve => setTimeout(resolve, 500));
			app.globalData.Request.post(app.globalData.ApiConstant.Message.getMessageHeadList, {},{showLoad: false}
			).then((res)=>{
				console.log(res)
				this.conversations = res.data
				let nowDate = Date.now()
				for(let item of this.conversations){
					if(item.product){
						if(item.product.imageUrls){
							item.previewImage = item.product.imageUrls.split(',')[0]
						}
					}
					item.unreadCount = 0
					item.lastMessage = ''
					item.lastMessageTime = this.formatTimeAgo(item.lastMessageTime) // + '小时前'
					item.name = item.sender.name
				}
			}).catch((err)=>{
				uni.showToast({ title: '获取消息异常', icon: 'none' });
			}).finally((res)=>{
			})

			this.conversations = [
			];
			this.isLoadingInitial = false;
		},
		loadMoreConversations() {
			if (this.isLoadingMore || this.noMoreData) return;
			this.isLoadingMore = true;
			this.page++;
			// 模拟加载更多
			setTimeout(() => {
				// 假设没有更多数据了
				// const newConversations = [ ... ];
				// this.conversations = [...this.conversations, ...newConversations];
				// if (newConversations.length < 10) { // 假设每页10条
				//  this.noMoreData = true;
				// }
				this.noMoreData = true; // 简单设置为没有更多
				this.isLoadingMore = false;
			}, 1000);
		},
		clearUnread() {
			uni.showModal({
				title: '提示',
				content: '确定要清除所有未读消息吗？（仅为演示，不会真清除）',
				success: (res) => {
					if (res.confirm) {
						this.conversations.forEach(conv => conv.unreadCount = 0);
						uni.showToast({ title: '未读已清除', icon: 'none' });
					}
				}
			});
		},
		gotoSearch() {
			uni.navigateTo({ url: '/pages/search/GlobalSearchPage' }); // 假设有全局搜索页
		},
		openConversation(conv) {
			// 根据 conv.id 或 conv.type 跳转到不同的聊天页或功能页
			console.log("Open conversation:", conv.id);
			uni.setStorageSync('receiver', {
				receiverPhoto: conv.sender.photo,
				receiverName: conv.sender.name,
			});
			wx.navigateTo({
				url: '/pages/tb/chat/chat?productId=' + conv.product.id + '&receiverId=' + conv.sender.userId
			})
			// if (conv.id === 'notification' || conv.id === 'interaction' || conv.id === 'xianyu_choice') {
			// 	uni.showToast({ title: `查看 ${conv.name}`, icon: 'none' });
			// 	// uni.navigateTo({ url: `/pages/message/SystemMessagePage?type=${conv.id}` });
			// } else {
			// 	// 示例：根据不同会话类型跳转到之前的 ChatPage
			// 	let chatType = 'type1'; // 默认
			// 	if (conv.name === '东晋正直的鱿鱼') { // 模拟和截图二相似
			// 		chatType = 'type2';
			// 	}
			// 	uni.navigateTo({ url: `/pages/chat/ChatPage?chatId=${conv.id}&chatType=${chatType}` });
			// }
		}
	}
};
</script>

<style lang="scss" scoped>
.message-list-page {
	background-color: #fff; // 页面背景色通常为白色
	min-height: 100vh;
	display: flex;
	flex-direction: column;
}

.top-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	height: 88rpx; // 模拟导航栏高度
	box-sizing: border-box;
	// position: sticky; // 如果希望顶部栏固定
	// top: 0;
	// background-color: #fff;
	// z-index: 100;

	.page-title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
	}
	.actions {
		display: flex;
		align-items: center;
		.action-item {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: #555;
			margin-left: 30rpx;
			text {
				margin-left: 6rpx;
			}
		}
	}
}

.search-bar-container {
	padding: 10rpx 30rpx 20rpx;
	// position: sticky; // 如果希望搜索框也固定
	// top: 88rpx; // top-bar 的高度
	// background-color: #fff;
	// z-index: 99;
	.search-bar {
		background-color: #f5f5f5;
		border-radius: 30rpx;
		padding: 15rpx 25rpx;
		display: flex;
		align-items: center;
		.placeholder {
			margin-left: 15rpx;
			font-size: 28rpx;
			color: #aaa;
		}
	}
}

.conversation-list {
	flex: 1; // 占据剩余空间
	background-color: #fff;
	.conversation-item {
		display: flex;
		align-items: center;
		padding: 24rpx 30rpx;
		position: relative;
		&:not(:last-child)::after {
			content: '';
			position: absolute;
			left: 120rpx; // 头像宽度 + padding
			right: 0;
			bottom: 0;
			height: 1px;
			background-color: #f0f0f0;
			transform: scaleY(0.5);
		}
		&.pinned { // 置顶样式 (如果需要)
			// background-color: #f9f9f9;
		}

		.avatar-container {
			position: relative;
			margin-right: 24rpx;
			flex-shrink: 0;
			.avatar {
				width: 96rpx;
				height: 96rpx;
				border-radius: 12rpx; // 方形圆角
				background-color: #eee; // 占位
			}
			.unread-badge {
				position: absolute;
				top: -8rpx;
				right: -8rpx;
				background-color: #fa3534; // 红色
				color: white;
				font-size: 20rpx;
				border-radius: 50%;
				padding: 0 8rpx; // 左右padding让圆形更饱满
				min-width: 32rpx; // 保证圆形
				height: 32rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				box-sizing: border-box;
				border: 2rpx solid #fff; // 白色描边
			}
			.mute-dot { // 免打扰红点
				position: absolute;
				top: 0rpx;
				right: 0rpx;
				background-color: #fa3534;
				width: 16rpx;
				height: 16rpx;
				border-radius: 50%;
				border: 2rpx solid #fff;
			}
			.status-icon { // 头像右下角的小图标
				position: absolute;
				bottom: -2rpx;
				right: -2rpx;
				width: 36rpx;
				height: 36rpx;
				// border-radius: 50%; // 如果小图标是圆的
				// background-color: #fff; // 可能有白色背景
			}
		}

		.content-container {
			flex-grow: 1;
			overflow: hidden; // 防止文字溢出
			margin-right: 20rpx; // 给右侧缩略图留空间

			.title-line {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 8rpx;
				.name {
					font-size: 30rpx;
					color: #333;
					font-weight: 500; // 默认不加粗，未读时加粗
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					flex-shrink: 1; // 允许名字被压缩
					margin-right: 10rpx;
					&.unread-name {
						font-weight: bold;
					}
				}
				.status-tag {
					font-size: 20rpx;
					color: #28a745; // 交易成功绿色
					background-color: #eaf6ec;
					padding: 2rpx 8rpx;
					border-radius: 4rpx;
					margin-left: 8rpx;
					flex-shrink: 0;
				}
				.time {
					font-size: 22rpx;
					color: #999;
					margin-left: auto; // 时间推到最右边
					flex-shrink: 0;
				}
			}

			.message-line {
				display: flex;
				align-items: center;
				justify-content: space-between;
				.last-message {
					font-size: 26rpx;
					color: #666;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					flex-grow: 1; // 占据尽可能多的空间
					&.unread-message {
						color: #333; // 未读消息颜色深一点
					}
				}
				.mute-icon {
					margin-left: 10rpx;
					flex-shrink: 0;
				}
			}
		}
		.preview-image {
			width: 80rpx;
			height: 80rpx;
			border-radius: 8rpx;
			flex-shrink: 0;
			background-color: #f0f0f0;
		}
	}
	.loading-more, .no-more, .empty-state {
		text-align: center;
		color: #999;
		font-size: 24rpx;
		padding: 30rpx 0;
	}
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 150rpx;
		.empty-icon {
			width: 200rpx; // 根据实际图片调整
			margin-bottom: 20rpx;
		}
	}
}
</style>